const express = require("express");

var router = express.Router();

const db = require("../model/db.js");

//添加
router.post("/", async (req, res) => {
    const data = await db.Movie.create(req.body)
    res.send(data)
})
//删除
router.delete("/:id", async (req, res) => {
    await db.Movie.deleteOne({ _id: req.params.id }) //条件对象
    res.send(true)
})
//查询所有的
router.get("/", async (req, res) => {
    let condition = {};
    if (req.query.key) {
        let exp = new RegExp(req.query.key, "i")//不区分大小写，模糊查询正则表达式
        condition = {
            $or: [
                { name: { $regex: exp } },
                { type: { $regex: exp } }
            ]
        }
    }
    let page = parseInt(req.query.page);
    let limit = parseInt(req.query.limit);
    if (!page) {
        page = 1;
    }
    if (!limit) {
        limit = 10
    }
    const data = await db.Movie.find(condition).skip((page - 1) * limit).limit(limit);
    const count = await db.Movie.countDocuments(condition);
    res.send({
        "code": 0,
        "msg": "",
        "count": count,
        "data": data
    })
})
//查询单个
router.get("/:id", async (req, res) => {
    const data = await db.Movie.findById(req.params.id);
    res.send({
        "code": 0,
        "msg": "",
        "count": 1,
        "data": data
    })
})
//修改
router.put("/:id", async (req, res) => {
    await db.Movie.updateOne(//条件对象
        { _id: req.params.id }, req.body)
    res.send(true)
})

module.exports = router;